package com.ynny.service;

import com.ynny.dao.BookDao;
import com.ynny.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class BookServiceImpl implements BookService {

    @Autowired
    BookDao bookDao;
    @Autowired
    UserDao userDao;

    @Transactional
    @Override
    public void buyBook(Integer userId, Integer bookId) {
        //1.查询图书的价格(查询图书是否存在)
        Integer price = bookDao.selectBookPrice(bookId);
        //2.减少图书的库存
        bookDao.updateBookStock(bookId);
        //3.减少用户的余额
        userDao.updateUserBalance(userId, price);
    }

    @Transactional
    @Override
    public int buyBookByProd(Integer userId, Integer bookId) {
        //1.查询图书的价格(查询图书是否存在)
        Integer price = bookDao.selectBookPrice(bookId);
        if (price == null) {
            return -1;//图书不存在
        }
        //2.减少图书的库存()
        //2.1 库存不足的情况
        //    查询库存是否足够

        int stock = bookDao.selectBookStock(bookId);
        if (stock <= 0) {
            return -2;//库存不足
        }
        //3.减少用户的余额
        //3.1 余额不足的情况
        //    查询余额是否足够
        int j = userDao.selectUserBalance(userId);
        if (j <=  0) {
            return -3;//余额不足
        }

        int i = bookDao.updateBookStock(bookId);
        if (i != 1) {
            return -4;//修改失败
        }

        //3.2 余额足够
        int res = userDao.updateUserBalance(userId, price);
        if (res == 1) {
            return 1;
        }
        return 0;
    }
}
